package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.exception.CustomException;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.builder.ArticleDtoBuilder;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private GreenTextScan greenTextScan;
    @Autowired
    private GreenImageScan greenImageScan;
    @Autowired
    private FileStorageService fileStorageService;
    //feign接口--同步数据
    @Autowired
    private IArticleClient client;
    @Autowired
    private WmUserMapper wmUserMapper;
    @Autowired
    private WmChannelMapper wmChannelMapper;
    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;
    @Autowired
    private Tess4jClient tess4jClient;


    /**
     * 自媒体文章审核
     *
     * @param id 自媒体文章id
     */
    @Override
    @Async
    @GlobalTransactional
    public void autoScanWmNews(Integer id) throws Exception {
        // 1. 通过文章id查询文章
        WmNews wmNews = wmNewsMapper.selectById(id);
        // 2. 判断文章是否存在，不存在则抛出异常
        if(null == wmNews){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 3. 获取文章的状态，判断是否进行机器审核
        if(wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())){
            //3.1 抽取文章的内容以及图片 封装为map
            Map<String,Object> map = handleTextAndImages(wmNews);

            // 自定义敏感词审核
            boolean isTextScan = handleSensitiveScan(map.get("textContent").toString(),wmNews);
            if (!isTextScan){
                return;
            }

            //3.2 发送文本到阿里云进行文本审核 如果审核不通过则更新文章的状态并返回原因
            isTextScan = handleTextScan(map.get("textContent").toString(),wmNews);
            if (!isTextScan){
                return;
            }

            //3.2 下载所有图片数据发送到阿里云进行图片神格 如果审核不通过则更新文章的状态并返回原因
            boolean isImageScan =  handleImageScan((List<String>)map.get("images"),wmNews);
            if(!isImageScan){
                return;
            }

            //3.4 调用Feign完成数据同步
            ResponseResult responseResult = saveAppArticle(wmNews);

            //3.5 更新文章状态和app_article表中的id到自媒体文章的表中
            if(!responseResult.getCode().equals(200)){
                throw new CustomException(AppHttpCodeEnum.SERVER_ERROR);
            }

            wmNews.setArticleId(Long.parseLong(responseResult.getData().toString()));

            updateWmNewStatus(wmNews,(short) 9,"文章审核通过");
        }
    }

    /**
     * 自定义敏感词库审核
     * @param textContent
     * @param wmNews
     * @return
     */
    private boolean handleSensitiveScan(String textContent, WmNews wmNews) {
        boolean flag = Boolean.TRUE;

        // 1. 查询数据库所有敏感词对象
        List<WmSensitive> sensitiveList = wmSensitiveMapper.selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));

        // 2. 得到敏感词字符集集合
        List<String> list = sensitiveList.stream().map(item -> item.getSensitives()).collect(Collectors.toList());

        // 3. 初始化DAF算法的大Map
        SensitiveWordUtil.initMap(list);

        // 4. 使用DAF算法完成文本审核
        Map<String, Integer> map = SensitiveWordUtil.matchWords(textContent);

        // 5. 如果审核失败则更新文章状态 5.1 返回失败原因
        if(null != map && map.size() > 0){
            updateWmNewStatus(wmNews,(short) 2,"自定义敏感词失败 -> "+ map);
            flag = false;
        }

        return flag;
    }

    /**
     * 完成数据同步
     * @param wmNews
     * @return
     */
    private ResponseResult saveAppArticle(WmNews wmNews) {
//        ArticleDto dto = new ArticleDto();
//        BeanUtils.copyProperties(wmNews,dto);
//
//        dto.setLayout(wmNews.getType());
//
//        // 查询作者相关信息
//        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
//        dto.setAuthorId((long)wmNews.getUserId());
//        if(null != wmUser){
//            dto.setAuthorName(wmUser.getName());
//        }
//
//        // 处理频道数据
//        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
//        if(null != wmChannel){
//            dto.setChannelName(wmChannel.getName());
//        }

        // 使用构造器设计模式
        ArticleDtoBuilder builder = new ArticleDtoBuilder(wmNews,wmChannelMapper,wmUserMapper);

        ArticleDto dto = builder.buildBeanCopy()
                .buildAuthor()
                .buildBasic()
                .buildChannel()
                .builder();

        ResponseResult responseResult = client.saveArticle(dto);
        return responseResult;
    }

    /**
     * 文章内容图片审核
     * @param images
     * @param wmNews
     * @return
     */
    private boolean handleImageScan(List<String> images, WmNews wmNews) throws Exception {
        boolean flag = true;
        if(images == null && images.size() == 0){
            return flag;
        }
        images = images.stream().distinct().collect(Collectors.toList());
        List<byte[]> imageList = new ArrayList<>();
        for (String img : images) {
            byte[] bytes = fileStorageService.downLoadFile(img);
            imageList.add(bytes);

            // 下载一张图片，识别一张图片并审核一张图片

            // 识别图片
            ByteArrayInputStream in = new ByteArrayInputStream(bytes);
            BufferedImage image = ImageIO.read(in);
            String str = tess4jClient.doOCR(image);

            // 审核图片
            boolean status = handleSensitiveScan(str, wmNews);
            if(!status){
                flag = false;
                return flag;
            }

        }

        Map map = greenImageScan.imageScan(imageList);
         flag = parseScanResponse(wmNews, flag, map, "图片");

         return flag;
    }

    /**
     * 文章内容文本审核
     * @param textContent
     * @param wmNews
     * @return
     */
    private boolean handleTextScan(String textContent, WmNews wmNews) throws Exception {
        boolean flag = true;
        Map map = greenTextScan.greeTextScan(textContent);

        flag = parseScanResponse(wmNews, flag, map,"文本");
        return flag;
    }

    private boolean parseScanResponse(WmNews wmNews, boolean flag, Map map,String text) {
        if(map != null){
            if("block".equals(map.get("suggestion"))){
                // 修改文章状态和返回审核信息
                updateWmNewStatus(wmNews,(short)2,text+"中存在违规内容");
                flag = false;
            }else if("review".equals(map.get("suggestion"))){
                updateWmNewStatus(wmNews,(short)3,text+"中存在不确定因素，需要人工审核");
                flag = false;
            }
        }
        return flag;
    }

    /**
     * 更新文章的状态以及失败原因
     * @param wmNews  原有数据
     * @param status  修改后状态
     * @param reason  失败原因
     */
    private void updateWmNewStatus(WmNews wmNews, short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);

        wmNewsMapper.updateById(wmNews);
    }

    /**
     * 获取文章中的内容以及图片并封装为Map对象返回
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        // 保存文本数据
        StringBuilder sb = new StringBuilder();
        // 保存图片数据
        List<String> images = new ArrayList<>();

        if (StringUtils.isNotEmpty(wmNews.getContent())) {
            List<Map> list= JSON.parseArray(wmNews.getContent(), Map.class);

            for (Map map : list) {
                if("image".equals(map.get("type"))){
                    images.add((String) map.get("value"));
                }else if("text".equals(map.get("type"))){
                    sb.append(map.get("value"));
                }
            }
        }

        // 获取文章的标题
        sb.append(wmNews.getTitle());

        // 获取文章封面图片
        if(StringUtils.isNotEmpty(wmNews.getImages())){
            String[] imgs = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(imgs));
        }

        Map<String,Object> map = new HashMap<>();
        map.put("textContent",sb);
        map.put("images",images);
        return map;
    }
}
